package com.qf.flash.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.event.FuckEvent;
import com.qf.flash.http.HttpManager;
import com.qf.flash.http.response.ScriptDetailResponse;
import com.qf.flash.model.CommentBean;
import com.qf.flash.model.Pay2SponsorBean;
import com.qf.flash.model.PayParam;
import com.qf.flash.model.ScriptRoleBean;
import com.qf.flash.mvp.contract.CommentContract;
import com.qf.flash.mvp.contract.ScriptDetailContract;
import com.qf.flash.mvp.contract.StartTeamContract;
import com.qf.flash.mvp.presenter.CommentPresenter;
import com.qf.flash.mvp.presenter.ScriptDetailPresenter;
import com.qf.flash.mvp.presenter.StartTeamPresenter;
import com.qf.flash.ui.home.adapter.GameCommentView;
import com.qf.flash.ui.home.adapter.RoleItem;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.widget.RatingBarView;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.RxUtils;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static android.text.Html.FROM_HTML_MODE_COMPACT;

/**
 * 创建日期：2020/2/23 on 20:36
 * 描述: 剧本详情
 * 作者:dxd
 */
public class ScriptDetailActivity extends BaseActivity implements ScriptDetailContract.View, CommentContract.View, StartTeamContract.View {


    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.iv_script_head)
    ImageView ivScriptHead;
    @BindView(R.id.tv_script_theme)
    TextView tvScriptTheme;
    @BindView(R.id.tv_script_name)
    TextView tvScriptName;
    @BindView(R.id.tv_script_author)
    TextView tvScriptAuthor;
    @BindView(R.id.tv_script_time)
    TextView tvScriptTime;
    @BindView(R.id.tfl_tag)
    TagFlowLayout tflTag;
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.iv_open_close)
    ImageView ivOpenClose;
    @BindView(R.id.rv_role)
    RecyclerView rvRole;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.rbv_star)
    RatingBarView rbvStar;
    @BindView(R.id.tv_total_comment)
    TextView tvTotalComment;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    private RVAdapter<Object> mCommentAdapter;
    private RVAdapter<ScriptRoleBean> mRoleAdapter;

    private ScriptDetailPresenter mGameDetailPresenter;
    private StartTeamPresenter mStartTeamPresenter;
    private CommentPresenter mCommentPresenter;

    private int page = 1;
    private String id;
    private boolean isOpen;
    private Pay2SponsorBean bean;
    private int position = -1;
    private ScriptDetailResponse response;

    public static void start(Activity activity, Pay2SponsorBean bean, int position) {
        Intent intent = new Intent(activity, ScriptDetailActivity.class);
        intent.putExtra("bean", bean);
        intent.putExtra("position", position);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String playId) {
        Intent intent = new Intent(activity, ScriptDetailActivity.class);
        intent.putExtra("playId", playId);
        activity.startActivity(intent);
    }

    @Override
    protected void initInject() {
        mGameDetailPresenter = new ScriptDetailPresenter();
        mCommentPresenter = new CommentPresenter();
        mStartTeamPresenter = new StartTeamPresenter();
        initPresenters(mGameDetailPresenter, mCommentPresenter, mStartTeamPresenter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_script_detail;
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("剧本详情");
        initRvRole();
        initCommentRv();
        initRefresh();
        bean = getIntent().getParcelableExtra("bean");
        id = getIntent().getStringExtra("playId");
        position = getIntent().getIntExtra("position", -1);
        if (bean != null) {
            id = bean.getPlayId();
            tvJoin.setVisibility(View.VISIBLE);
        }

        mGameDetailPresenter.getScriptDetail(id);
        mGameDetailPresenter.getScriptRole(id);
        mCommentPresenter.getCommentData(id, page);
    }

    private void initTag(List<String> tags) {
        tflTag.setAdapter(new TagAdapter<String>(tags) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv_hot = (TextView) LayoutInflater.from(ScriptDetailActivity.this).inflate(R.layout.item_tag, tflTag, false);
                tv_hot.setText(s);
                return tv_hot;
            }
        });

    }

    private void initRefresh() {
        mRefresh.setEnableRefresh(false);
        mRefresh.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mCommentPresenter.getCommentData(id, page);
        });
    }

    private void initRvRole() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvRole.setLayoutManager(linearLayoutManager);
        mRoleAdapter = new RVAdapter<>(new RoleItem());
        rvRole.setAdapter(mRoleAdapter);
        mRoleAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                gotoRolePagerActivity(position);
            }
        });
    }

    private void gotoRolePagerActivity(int position) {
        ArrayList<ScriptRoleBean> roleBeans = (ArrayList<ScriptRoleBean>) mRoleAdapter.getDatas();
        RolePagerActivity.start(this, roleBeans, position);
    }


    private void initCommentRv() {
        rvComment.setLayoutManager(new LinearLayoutManager(this));
        mCommentAdapter = new RVAdapter<>(new GameCommentView());
        rvComment.setAdapter(mCommentAdapter);
    }


    @OnClick({R.id.tv_top_back, R.id.tv_join, R.id.iv_open_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.iv_open_close:
                onArrowClick();
                break;
            case R.id.tv_join:
                if (bean == null)
                    return;
                if (response != null)
                    bean.setMoney(response.getDownpayment());
                if (bean.getMoney() == 0) {
                    mStartTeamPresenter.startTeam(bean);
                } else {
                    sponsorGame();
                }
                break;
        }
    }

    private void sponsorGame() {
        if (bean == null)
            return;
        if (TextUtils.isEmpty(bean.getTeamName())) {
            FlashLib.showToast("请输入组队名称");
            EventBus.getDefault().post(new FuckEvent(position));
            finish();
            return;
        }
        if (TextUtils.isEmpty(bean.getStartTime())) {
            FlashLib.showToast("请选择时间");
            EventBus.getDefault().post(new FuckEvent(position));
            finish();
            return;
        }
        //校验时间
        HttpManager.getInstance()
                .getGsonHttpApi()
                .GAME_VALIDE(UserMgr.getInstance().getLoginUser().getUid(), bean.getStartTime())
                .compose(RxUtils.handleResult())
                .compose(RxUtils.io_main())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {
                        Pay2SponsorDialogFragment.newInstarnce(bean)
                                .show(getSupportFragmentManager());
                    }

                    @Override
                    public void onError(Throwable e) {
                        FlashLib.showToast(e.getMessage());
                        EventBus.getDefault().post(new FuckEvent(position));
                        finish();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    @Override
    public void setCommentData(List<CommentBean> commentBeans, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, false);
        List<Object> datas = mCommentAdapter.getDatas();
        datas.addAll(new ArrayList<>(commentBeans));
        mCommentAdapter.notifyDataSetChanged();
        mRefresh.setEnableLoadMore(page < totalPage);
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, false);
    }


    private void onArrowClick() {
        if (isOpen) {
            isOpen = false;
            tvIntroduce.setMaxLines(3);
            ivOpenClose.setRotation(0);
        } else {
            isOpen = true;
            tvIntroduce.setMaxLines(Integer.MAX_VALUE);
            ivOpenClose.setRotation(180);
        }
    }

    @Override
    public void setScriptDetail(ScriptDetailResponse response) {
        if (response == null)
            return;
        this.response = response;
        tvScriptName.setText(response.getName());
        tvScriptAuthor.setText("作者: " + response.getAuthor());
        tvScriptTime.setText("时长: " + response.getGameLength());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvIntroduce.setText(Html.fromHtml(response.getContent().replace("\n", "<br>"), FROM_HTML_MODE_COMPACT));
        } else {
            tvIntroduce.setText(Html.fromHtml(response.getContent().replace("\n", "<br>")));
        }
        ImageLoader.loadRoundCorners(this, response.getImage(), ivScriptHead, 5);
        tvScriptTheme.setText(response.getTypeName());
        initTag(response.getTags());


        //剧本评分
        tvScore.setText(response.getResponseScole() + "");
        rbvStar.setStar(Math.round(response.getResponseScole()), false);
        tvTotalComment.setText(response.getResponseCount() + "次评论");

    }

    @Override
    public void setScriptRole(List<ScriptRoleBean> roleBeans) {
        mRoleAdapter.setDatas(roleBeans);
    }

    @Override
    public void startSuccess(PayParam payParam) {
        OrderPaySuccessActivity.start(this, payParam.getOrderId(), true);
    }
}
